package com.i72.freeway;

import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @author jiangj
 * @version 1.0.0
 * @ClassName ClassUtils.java
 * @Description TODO
 * @createTime 2021年12月28日 15:02:00
 */
public class ClassUtils {

    public static List<Class> getApiClasses(String apiPackage) {
        // 扫描包下带有@Path注解的api
        TypeFilter typeFilter = (metadataReader, metadataReaderFactory) -> {
            String pathAnnotation = FreewayPath.class.getName();
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            return annotationMetadata.getAnnotationTypes().contains(pathAnnotation);
        };
        return SpringResourceHelper.getClasses(apiPackage, new TypeFilter[] { typeFilter }, null);
    }

    public static List<Class> getClasses(String packageName, Class clazz) {
        TypeFilter typeFilter = (metadataReader, metadataReaderFactory) -> {
            ClassMetadata classMetadata = metadataReader.getClassMetadata();
            return clazz.getName().equals(classMetadata.getSuperClassName());
        };
        return SpringResourceHelper.getClasses(packageName, new TypeFilter[] { typeFilter }, null);
    }

    // 例如com.swj.api.usercenter
    public static String getAppNode(Class clazz) {
        String result = null;
        Map<String, String> mappings = FreewayConfig.getServiceMappings();
        if(mappings!=null && mappings.keySet().size()>0){
        //if (MapUtils.isNotEmpty(mappings)) {
            result = mappings.entrySet()
                    .stream()
                    .filter(entry -> clazz.getPackage().getName().startsWith(entry.getKey()))
                    .map(Map.Entry::getValue)
                    .findFirst()
                    .orElse(null);
        }

        if (StringUtils.isEmpty(result)) {
            String[] packageSplit = clazz.getPackage().getName().split("\\.");
            for (int i = 0; i < packageSplit.length; i++) {
                /*
                if (packageSplit[i].equalsIgnoreCase("api")) {
                    result = packageSplit[i + 1];
                    break;
                }*/
                if (packageSplit[i].equalsIgnoreCase("freeway")) {
                    result = packageSplit[i + 2];
                    break;
                }
            }
        }

        if (StringUtils.isEmpty(result)) {
            throw new IllegalArgumentException("Can not get appNode name from class: " + clazz.getName());
        }
        return result;
    }


}
